package com.traffic.between.service;

import java.net.URI;
import java.nio.charset.Charset;
import java.security.MessageDigest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.traffic.between.config.BetweenProperties;
import com.traffic.between.util.HTMLUtils;

@SuppressWarnings("deprecation")
public class DanYuankejiServiceImpl {
	private static Logger logger = Logger.getLogger(DanYuankejiServiceImpl.class);
	public static DanYuankejiServiceImpl service = new DanYuankejiServiceImpl();

	private static String HOST_ORDER_PATH = BetweenProperties.DYKJ_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.DYKJ_ORDERSTATUS_URL;
	private static String DYKJ_APPKEY = BetweenProperties.DYKJ_APPKEY;
	private static String DYKJ_SECURITYKEY = BetweenProperties.DYKJ_SECURITYKEY;

	@SuppressWarnings({ "resource" })
	public String order(String productId, String phoneNo, String cstmOrderNo) {
		
		String result = "";

		String action = "charge";

		/**
		 * 参数 : 固定： action:charge 必填：userid:客户名 password:密码 phone:充值号码
		 * mbytes:流量数
		 * 
		 * 可选： product: 产品ID mytype:漫游类型 linkid:引用ID
		 * 
		 * 2. 返回值 : XML格式,UTF-8编码 说明: phone:要充流量的11位手机号码， mbytes:流量数，
		 * 默认单位M，充1GB流量包可以填 1024,1024M,1024MB,1G,
		 * product:产品ID，指定要使用的产品，不填自动按价格优先选择 mytype:漫游类型， 0全国漫游,1省内漫游，不填自动按价格优
		 * linkid:引用ID，客户方提供的ID号，在状态中原样返回
		 * 
		 */
		// 参数
		String params = "action=" + action + "&userid=" + DYKJ_APPKEY + "&phone=" + phoneNo + "&mbytes=" + productId
				+ "&password=" + DYKJ_SECURITYKEY;
		logger.info("bsm- 单元科技订单DanYuankejiServiceImpl.order() 订购请求params<>:"+params);
		HttpClient httpClient = new DefaultHttpClient();
		// 连接时间，指的是连接一个url的连接等待时间。 超时报异常
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
		// 数据传输时间，指的是连接上一个url，获取response的返回等待时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
		// Get请求
		HttpGet httpget = new HttpGet(HOST_ORDER_PATH);
		try {
			httpget.setURI(new URI(httpget.getURI().toString() + "?" + params.trim()));

			// 发送请求
			HttpResponse httpResponse = httpClient.execute(httpget);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return "{\"resultCode\": \"01\",\"resultMsg\":\"订单异常\"}";
			}

			// 获取返回数据
			HttpEntity entity = httpResponse.getEntity();
			String body = EntityUtils.toString(entity, Charset.forName("UTF-8"));
			body = body.replaceFirst("/>", " />");

			logger.info("bsm- 单元科技订单DanYuankejiServiceImpl.order() 订购请求response:" + body);
			// body = HTMLUtils.getElement(body);
			String bodyreturn = HTMLUtils.match(body, "root", "return");
			String bodyinfo = HTMLUtils.match(body, "root", "info");
			String bodytaskid = HTMLUtils.match(body, "root", "taskid");

			// 返回0为充值请求提交成功，其他错误码为失败
			if ("0".equals(bodyreturn) && "成功".equals(bodyinfo)) {
				result = "{\"resultCode\": \"00\",\"resultMsg\":\"订单成功\",\"orderId\":" + bodytaskid + "}";
			} else {
				result = "{\"resultCode\": \"01\",\"resultMsg\":" + bodyinfo + "}";
			}
			if (entity != null) {
				EntityUtils.consume(entity);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpget.releaseConnection();
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

	@SuppressWarnings({ "resource" })
	public String orderStatus(String cstmOrderNo) {

		logger.info("bsm- 单元科技状态DanYuankejiServiceImpl.orderStatus() 查询请求cstmOrderNo = " + cstmOrderNo);

		String result = "";
		String action = "querystatus";

		/**
		 * 1. 查客户状态 参数 : 固定：action:querystatus 必填：userid:客户名 password:密码
		 * taskid:订单号
		 * 
		 */
		String params = "action=" + action + "&userid=" + DYKJ_APPKEY + "&password=" + DYKJ_SECURITYKEY + "&taskid="
				+ cstmOrderNo;

		HttpClient httpClient = new DefaultHttpClient();
		// 连接时间，指的是连接一个url的连接等待时间。 超时报异常
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
		// 数据传输时间，指的是连接上一个url，获取response的返回等待时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
		// Get请求
		HttpGet httpget = new HttpGet(HOST_ORDERSTATUS_PATH);
		try {
			httpget.setURI(new URI(httpget.getURI().toString() + "?" + params.trim()));

			// 发送请求
			HttpResponse httpResponse = httpClient.execute(httpget);
			int statusCode = httpResponse.getStatusLine().getStatusCode();

			if (statusCode != HttpStatus.SC_OK) {
				logger.error("Method failed:" + httpResponse.getStatusLine());
				return "{\"resultCode\": \"01\",\"resultMsg\":\"订单异常\"}";
			}

			// 获取返回数据
			HttpEntity entity = httpResponse.getEntity();
			String body = EntityUtils.toString(entity, Charset.forName("UTF-8"));
			body = body.replaceFirst("/>", " />");
			logger.info("bsm- 单元科技状态DanYuankejiServiceImpl.orderStatus() 查询响应response:" + body);
			String bodyreturn = HTMLUtils.match(body, "root", "return");
			String bodyinfo = HTMLUtils.match(body, "root", "info");
			String code = HTMLUtils.match(body, "root", "code");
			 //当Info=成功， return =0 的时候表示订单成功
			if ("0".equals(bodyreturn) && "成功".equals(bodyinfo)) {
				if ("0".equals(code)) {
					result = "{\"resultCode\": \"00\",\"resultMsg\":\"订购成功\"}";
				} else {
					result = "{\"resultCode\": \"01\",\"resultMsg\":\"订购失败\"}";
				}
			} else {
				result = "{\"resultCode\": \"02\",\"resultMsg\":\"订购中\"}";
			}
			if (entity != null) {
				EntityUtils.consume(entity);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("bsm- 单元科技订购请求上游异常:" + e);
		} finally {
			httpget.releaseConnection();
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		return md5StrBuff.toString().toLowerCase();// 字母小写
	}
}
